using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Framework.Manager
{
    public enum LoadState
    {
        None = 0,       // 尚未开始
        Loading = 1,    // 加载中
        Loaded = 2,     // 加载完成
    }
    
    public class BundleRef
    {
        public AssetBundle bundle;
        public int refNum;
        public AssetBundleCreateRequest request;
        public string assetPath;
        public LoadState state;
        public int waitNum;
    
        public BundleRef(string path)
        {
            assetPath = path;
            Clear();
        }
        
        public void Unload(bool unloadAllLoadedObjects)
        {
            // UnityEngine.Debug.Log("[BundleRef][Unload] " + assetName);

            // bundle 为空, 直接返回
            if (bundle == null)
            {
                return;
            }

            // 相关加载可能还在继续, 这里只减去引用值
            if (request != null && !request.isDone)
            {
                refNum -= 1;
                return;
            }

            bundle.Unload(unloadAllLoadedObjects);

            Clear();
        }
        
        private void Clear()
        {
            bundle = null;
            refNum = 0;
            state = LoadState.None;
            request = null;
            waitNum = 0;
        }
    }
}